package com.rp.system.user.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.rp.common.config.redis.RedisUtil;
import com.rp.common.config.shiro.ShiroConfig;
import com.rp.common.utils.*;

import com.rp.system.user.entity.SysUserRole;
import com.rp.system.user.model.UpdatePassWordModel;
import com.rp.system.user.service.*;
import com.rp.system.user.entity.SysUser;
import com.rp.system.user.mapper.SysUserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author vicente
 * @since 2020-11-23
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private RedisUtil redisUtil;

    public static String KEY_STRING = "system:user";

    /**
     * @Author HuJingYu
     * @Date 14:11 2021-03-08
     * @Description 默认密码
     * @param null
     * @return
     */
    public static String DEFAULT_PASSWORD = "123456";

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysPermissionService sysPermissionService;

    @Override
    public boolean save(SysUser sysUser) {
        if(NullIs.isEmpty(sysUser.getPassword())){
            sysUser.setPassword(DEFAULT_PASSWORD);
        }
        sysUser.setClientId(CreateRandom.createRandomCharData(12));
        sysUser.setSalt(CreateRandom.createRandomCharData(32));
        sysUser.setPassword(Md5PassWordUtil.getMd5(sysUser.getPassword(), sysUser.getUsername() + sysUser.getSalt(), ShiroConfig.HASH_ITERATIONS));
        boolean boo = sysUser.insert();
        if(!NullIs.isEmpty(sysUser.getRoleIdList())){
            boolean boo3 = sysUserRoleService.insertOrDelete(sysUser.getRoleIdList(),sysUser.getId());
        }
        return boo;
    }

    @Override
    public boolean updateById(SysUser sysUser) {
        if(!NullIs.isEmpty(sysUser.getPassword())){
            sysUser.setSalt(CreateRandom.createRandomCharData(32));
            sysUser.setPassword(Md5PassWordUtil.getMd5(sysUser.getPassword(), sysUser.getUsername() + sysUser.getSalt(), ShiroConfig.HASH_ITERATIONS));
        }
        boolean boo = super.updateById(sysUser);

        if(!NullIs.isEmpty(sysUser.getRoleIdList())){
            if(!NullIs.isEmpty(sysUser.getRoleIdList())){
                boolean boo3 = sysUserRoleService.insertOrDelete(sysUser.getRoleIdList(),sysUser.getId());
            }
        }
        return boo;
    }


    @Override
    public SysUser findSysUserByUsername(String username) {
        return showUser(username);
    }

    @Override
    public SysUser showUser(String username) {

        String key = KEY_STRING + ":" + username;
        //缓存存在
        if (redisUtil.hasKey(key)) {
            System.out.println("showUser直接取缓存数据");
            return (SysUser)redisUtil.get(key);
        } else {
            SysUser sysUser = sysUserMapper.showUser(username);
            if(NullIs.isEmpty(sysUser)){
                return sysUser;
            }
            sysUser.setRoleIdList(sysUser.getRoleList().stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
            sysUser.setRoleName(CollUtil.join(sysUser.getRoleList().stream().map(SysUserRole::getRoleName).collect(Collectors.toList()), ","));
            if(!NullIs.isEmpty(sysUser.getRoleIdList())){
                sysUser.setPermissionPermsList(sysPermissionService.getPermissionPermsByRoleIds(sysUser.getRoleIdList()));
            }
            System.out.println("sysUser++++++++++++++++" + sysUser);
            redisUtil.set(key, sysUser);
            return sysUser;
        }
    }

    @Override
    public IPage<SysUser> selectMyPage(IPage<SysUser> page, Wrapper<SysUser> queryWrapper) {
        IPage<SysUser> pages = sysUserMapper.selectMyPage(page, queryWrapper);

        List<SysUser> list = new LinkedList<>();
        for (SysUser sysUser : pages.getRecords()){


            sysUser.setRoleIdList(sysUser.getRoleList().stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
            sysUser.setRoleName(CollUtil.join(sysUser.getRoleList().stream().map(SysUserRole::getRoleName).collect(Collectors.toList()), ","));
            sysUser.setRoleList(null);
            list.add(sysUser);
        }
        pages.setRecords(list);
        return pages;
    }

    @Override
    public String selectClientSecret(String clientId) {
        return sysUserMapper.selectClientSecret(clientId);
    }

    @Override
    public Boolean updateClientSecret(String username, String clientSecret) {
        return sysUserMapper.updateClientSecret(username, clientSecret);
    }

    @Override
    public Boolean updatePassWord(UpdatePassWordModel updatePassWordModel) {
        SysUser sysUser = super.getById(updatePassWordModel.getId());
        String oldPassword = Md5PassWordUtil.getMd5(updatePassWordModel.getOldPassword(), sysUser.getUsername() + sysUser.getSalt(), ShiroConfig.HASH_ITERATIONS);
        if(!oldPassword.equals(sysUser.getPassword())){
            return false;
        }
        return updateById(new SysUser().setId(sysUser.getId()).setUsername(sysUser.getUsername()).setPassword(updatePassWordModel.getNewPassword()));
    }
}
